# encoding: utf-8
'''
Created on 2014-12-13
@name: 牛顿迭代法
@chapter: 2.3
@author: revol
'''
from solve import Solve
import math

class NewtonIteration(Solve):
    '''
    牛顿迭代法
    '''


    def __init__(self, data=[]):
        Solve.__init__(self, data)
        self.x0=0.5
        if data:
            self.calc(data)
        self._name=u'牛顿迭代法'
        self._description=("牛顿迭代法是通过将非线性方程线性化得到迭代序列的一种方式。\n本例采用 '例2-15' 的条件。"
                            "\nF(x)=x*e^x-1\nf(x)=e^x+xe^x\n迭代公式：x_(k+1)=x_k-(x_k-e^-x_k)/(1+x_k)\nx0=0.5")
        self._paramenters=[{'name':'accuracy','type':self.typeFLOAT}]
        
    def n(self,x):
        return x-(x-math.exp(-x))/(1+x)
    
    def calc(self, data):
            Solve.calc(self, data)
            accuracy=data['accuracy']
            x=self.x0        
            x1=self.n(x)
            while(abs(x-x1)>accuracy):
                x=self.n(x1)
                x1=self.n(x)
            self._result=x
            return x
    def getOutput(self):
        out=u"参数：\n\t精度： %f \n近似根： %f \n" %(self._data['accuracy'],self._result)
        return out
    
if __name__ == '__main__':
    data={'accuracy':0.000001}
    test=NewtonIteration(data)
    print test.getOutput()
    print test.getResult()
    print test.getDescription()
    print test.getParamenters()